<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable style="width: 240px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable style="width: 240px">
          <el-option
            v-for="dict in priorityOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交付日期">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词搜索"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit-outline"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown size="mini" @command="handleSelectCommand">
          <el-button type="info" plain size="mini">
            选择操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="selectCurrentPage">全选当前页</el-dropdown-item>
            <el-dropdown-item command="clearAllSelection">清空所有选择</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!multiple">
        <span class="selected-info">
          已选择 <strong>{{ ids.length }}</strong> 项
        </span>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="multipleTable" v-loading="loading" :data="orderList" :row-key="getRowKeys" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="生产订单编号" align="center" prop="prodOrderCode">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="handleViewDetail(scope.row)">{{ scope.row.prodOrderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="销售单号" align="center" prop="salesOrderCode" />
      <el-table-column label="交付日期" align="center" prop="deliveryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <el-tag :type="getPriorityTagType(scope.row.priority)">{{ getPriorityLabel(scope.row.priority) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生产状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ statusFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleUpdate" icon="el-icon-edit">修改</el-dropdown-item>
              <el-dropdown-item command="handleDelete" icon="el-icon-delete">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listProductionOrder, updateProductionOrder, delProductionOrder } from "@/api/sc/productionOrder";
import { getProduct } from "@/api/basic/product";

export default {
  name: "shengchandingdan",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组（当前页）
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产订单表格数据
      orderList: [],
      // 状态数据字典
      statusOptions: [],
      // 优先级数据字典
      priorityOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prodOrderCode: undefined,
        salesOrderCode: undefined,
        status: undefined,
        priority: undefined,
        keyword: undefined
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sc_production_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sc_priority_type").then(response => {
      this.priorityOptions = response.data;
      console.log("优先级字典数据:", this.priorityOptions);
    });
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/order' || to.name === 'shengchandingdan') {
        console.log('生产订单页面路由变化，刷新数据');
        this.getList();
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('生产订单查询参数变化，刷新数据');
          this.getList();
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取行的唯一标识，用于跨页选择
    getRowKeys(row) {
      return row.productionOrderId;
    },
    /** 查询生产订单列表 */
    getList() {
      this.loading = true;
      // 使用自定义的日期范围参数名称，确保传递的是DeliveryDate而不是默认的CreateTime
      const params = {...this.queryParams};
      params.params = params.params || {};

      if (this.dateRange && this.dateRange.length > 0) {
        params.params['beginDeliveryDate'] = this.dateRange[0];
        params.params['endDeliveryDate'] = this.dateRange[1];
      }

      listProductionOrder(params).then(response => {
        this.orderList = response.rows || [];
        this.total = response.total;
        this.loading = false;

        console.log("订单列表数据:", this.orderList.length, "条");


      });
    },

    /** 获取产品信息 */
    getProductInfo() {
      // 处理每个订单的产品信息
      this.orderList.forEach(order => {
        if (order.products && order.products.length > 0) {
          // 为每个产品获取详细信息
          order.products.forEach(product => {
            if (product.productId) {
              getProduct(product.productId).then(response => {
                const productData = response.data;
                if (productData) {
                  product.productCode = productData.productcode;
                  product.productName = productData.productname;
                  product.unit = productData.unit;
                  product.specification = productData.specificationnumber;

                  // 直接在产品对象中设置属性，不再将产品信息复制到订单对象
                }
              }).catch(error => {
                console.error("获取产品信息失败:", error);
              });
            }
          });
        }
      });
    },
    // 状态字典翻译
    statusFormat(row) {
      // 从字典中查找对应的标签
      for (let i = 0; i < this.statusOptions.length; i++) {
        if (this.statusOptions[i].dictValue == row.status) {
          return this.statusOptions[i].dictLabel;
        }
      }
      // 如果找不到，返回原始值
      return row.status;
    },
    // 获取优先级标签
    getPriorityLabel(priority) {
      // 从字典中查找对应的标签
      for (let i = 0; i < this.priorityOptions.length; i++) {
        if (this.priorityOptions[i].dictValue == priority) {
          return this.priorityOptions[i].dictLabel;
        }
      }
      // 如果找不到，返回原始值
      return priority;
    },
    // 获取优先级标签类型
    getPriorityTagType(priority) {
      // 根据优先级设置不同的标签类型
      if (priority == 1) return 'danger';
      if (priority == 2) return 'warning';
      if (priority == 3) return '';
      if (priority == 4) return 'info';
      if (priority == 5) return 'success';
      return '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据 - 使用Element UI原生跨页选择
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productionOrderId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;

      console.log('选择变化:', selection.length, '项');
      console.log('选中的ID:', this.ids);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/sc/order/add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.productionOrderId || this.ids
      this.$router.push({ path: "/sc/order/edit", query: { id: id } });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids, orderCodes, ordersToCheck;

      if (row) {
        // 单个删除
        ids = row.productionOrderId;
        orderCodes = [row.prodOrderCode];
        ordersToCheck = [row];
      } else {
        // 批量删除 - 使用Element UI原生方式获取选中数据
        const selectedRows = this.$refs.multipleTable.selection;
        if (!selectedRows || selectedRows.length === 0) {
          this.$modal.msgWarning("请选择要删除的订单");
          return;
        }

        ids = selectedRows.map(order => order.productionOrderId);
        orderCodes = selectedRows.map(order => order.prodOrderCode);
        ordersToCheck = selectedRows;
      }

      // 检查是否可以删除
      if (!this.canDeleteOrders(ordersToCheck)) {
        this.$modal.msgError("选中的订单中包含已完成或进行中的订单，无法删除");
        return;
      }

      const message = row
        ? `是否确认删除生产订单编号为"${row.prodOrderCode}"的数据项?`
        : `是否确认删除选中的${orderCodes.length}个生产订单?`;

      this.$modal.confirm(message).then(() => {
        this.loading = true;
        return delProductionOrder(ids);
      }).then(() => {
        this.loading = false;
        // 删除成功后清空选择状态
        if (!row) {
          this.$refs.multipleTable.clearSelection();
        }
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 批量删除按钮操作 */
    handleBatchDelete() {
      this.handleDelete();
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log("export");
    },
    /** 导入按钮操作 */
    handleImport() {
      console.log("import");
    },
    /** 操作命令 */
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    handleViewDetail(row) {
      this.$router.push({
        path: "/sc/order/detail",
        query: {
          id: row.productionOrderId,
          prodOrderCode: row.prodOrderCode
        }
      });
    },

    /** 获取选中订单的编号列表 */
    getSelectedOrderCodes() {
      return this.getSelectedOrders().map(order => order.prodOrderCode);
    },

    /** 获取选中的订单对象列表 */
    getSelectedOrders() {
      return this.orderList.filter(order => this.ids.includes(order.productionOrderId));
    },

    /** 检查订单是否可以删除 */
    canDeleteOrders(orders) {
      // 检查订单状态，不能删除已完成(3)或进行中(2)的订单
      return orders.every(order => {
        const status = order.status;
        return status !== '2' && status !== '3'; // 2=进行中, 3=已完成
      });
    },



    /** 处理选择操作命令 */
    handleSelectCommand(command) {
      switch (command) {
        case 'selectCurrentPage':
          this.selectCurrentPage();
          break;
        case 'clearAllSelection':
          this.clearAllSelection();
          break;
      }
    },

    /** 全选当前页 */
    selectCurrentPage() {
      this.orderList.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, true);
      });
      this.$message.success(`已选择当前页 ${this.orderList.length} 项`);
    },

    /** 清空所有选择 */
    clearAllSelection() {
      this.$refs.multipleTable.clearSelection();
      this.$message.success('已清空所有选择');
    }

  }
};
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.selected-info {
  color: #606266;
  font-size: 14px;
  line-height: 28px;
  margin-left: 10px;
}

.selected-info strong {
  color: #409EFF;
}

.select-all-tip {
  color: #E6A23C;
  font-size: 12px;
}

.cross-page-tip {
  color: #909399;
  font-size: 12px;
}
</style>
